﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Shared.Method;
using Shared.Model;
using Client;
using StationTestDll;
using Shared.SoftMethod;

namespace ModemWrite
{
    public partial class FormMsgCheck : UserControl
    {
        private string _stationIp = null;

        private string _localIp = null;
        private int _localPort = 0;

        private string _modemIp = null;
        private string _modemUser = null;
        private string _modemPwd = null;

        private int _myFormNum = 0;

        private long _nodeId = 0;
        //private YcdTelnetSecond _telnet = null;
        //private string _ifReset = "0";

        //增加一个事件传递正在写入信息的指令
        public event Action<int> OnWrite;

        private string _log = "";

        //所有的产品类型信息
        private List<Device_Type> _listType = null;

        //private int _testNum = 0;

        //获取初始化数据
        public FormMsgCheck(string localIp, int localPort,
            string modemIp, string modemUser, string modemPwd,
            int formNum, List<Device_Type> listType, string stationIp = "127.0.0.1")
        {
            _stationIp = stationIp;

            _localIp = localIp;
            _localPort = localPort;

            _modemIp = modemIp;
            _modemUser = modemUser;
            _modemPwd = modemPwd;

            _myFormNum = formNum;

            _listType = listType;

            //_ifReset = ifReset;

            if (string.IsNullOrEmpty(localIp)
                || string.IsNullOrEmpty(modemIp)
                || string.IsNullOrEmpty(modemUser)
                || string.IsNullOrEmpty(modemPwd)
                || localPort <= 1024)
            {
                //初始化的参数不正确
                MessageBox.Show(string.Format("窗口：{0}，初始化参数不正确", _myFormNum));
                this.Dispose();//销毁窗口
            }

            //从APPCONFIG获取配置
            string nodeId = AppSetting.GetValue("StationNodeId");
            if (string.IsNullOrEmpty(nodeId) == false) long.TryParse(nodeId, out _nodeId);

            InitializeComponent();
        }

        //输入MAC
        private void textBoxMacAddr_KeyPress(object sender, KeyPressEventArgs e)
        {
            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                e.Handled = true;
                if (this.textBoxMacAddr.Text.Trim().Length != 12)
                {
                    AppendRichTextBox("MAC地址不为12位数");
                    this.textBoxMacAddr.Clear();
                    this.textBoxMacAddr.Focus();
                }
                else
                {
                    //判断MAC是否已经绑定过SN号码，如果已经绑定了，则直接开始写入信息
                    Action d = new Action(CheckMessage);
                    d.BeginInvoke(null, null);
                }
            }
            else if ((e.KeyChar >= 'a' && e.KeyChar <= 'f')
                || (e.KeyChar >= 'A' && e.KeyChar <= 'F')
                || (e.KeyChar >= '0' && e.KeyChar <= '9')
                || (e.KeyChar == 8))
            {
                //判断是否位16进制字符，将小写全部转为大写
                e.Handled = false;
            }
            else
            {
                MessageBox.Show("只能输入数字和A-F");
                e.Handled = true;
            }
        }

        private void CheckMessage()
        {
            SetTextBoxReadOnly(true);

            string mac = this.textBoxMacAddr.Text.Trim();

            _log = "";

            OnWrite?.Invoke(_myFormNum);//发送正在写入信息的指令

            //判断此MAC地址是否已经存在了
            if (PublicData.ListAddress.ContainsKey(mac))
            {
                AppendRichTextBox("此MAC地址正在其他窗口使用，请勿重复扫描");
                SetTextBoxReadOnly(false);
                MacFocus();
                return;
            }
            else
            {
                PublicData.ListAddress.Add(mac, _myFormNum);
            }

            //判断是否需要进行此工序
            bool hasChecked = ProductCheck(mac);

            if (hasChecked)
            {
                AppendRichTextBox("此产品已经通过了信息检查，无需再次检查");

                //删除相关的MAC信息
                FinallyDone(mac, true);
                return;
            }

            //到数据库中查找是否存在相应的MAC
            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere();
            deviceW.MACAddr = mac;

            var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);
            if (selectDevice.result == false)
            {
                AppendRichTextBox("未能在数据库中找到MAC地址对应的数据，检查失败");

                //删除相关的MAC信息
                FinallyDone(mac);
                return;
            }

            //获取产品型号的相关数据
            var deviceType = GetDeviceType(selectDevice.value[0].DeviceType, selectDevice.value[0].HW_PROVINCE_NAME);

            if (deviceType == null)
            {
                AppendRichTextBox("未能获取产品的类型信息");

                FinallyDone(mac);
                return;
            }

            //显示正在测试当中
            SetTestState(true, "WAITFOR");

            //PING光猫
            int pingOkTimes = 0;
            for (int i = 0; i < 80; i++)
            {
                if (PingBaseClass.PingTest(_localIp, _modemIp))
                {
                    pingOkTimes++;
                    if (pingOkTimes >= 4)
                        break;
                }
                else
                {
                    pingOkTimes = 0;
                }
                System.Threading.Thread.Sleep(500);
            }

            if (pingOkTimes < 4)
            {
                AppendRichTextBox("未能成功PING通光猫");
                FinallyDone(mac);
                return;
            }

            //尝试5次1秒一次
            SetTestState(false, "TESTING");

            ////初始化telnet
            YcdTelnetSecond tel = null;
            for (int i = 0; i < 3; i++)
            {
                ////初始化telnet
                //tel = TelnetModem();

                if (_portOffset >= 800) _portOffset = 0;
                _portOffset++;

                tel = YcdTelnetMethod.TelnetModem(_localIp, _modemIp, _localPort + _portOffset, 23, _modemUser, _modemPwd);



                if (tel == null)
                {
                    AppendRichTextBox("TELNET光猫失败");
                }
                else
                {
                    break;
                }

                System.Threading.Thread.Sleep(5000);
            }

            if (tel == null)
            {
                FinallyDone(mac);
                return;
            }

            //获取光猫上的MAC地址，并绑定MAC与YCDMAC
            string ycdMac = MacClass.GetModemMacAddress(tel);

            #region OLD逻辑
            //如果MAC地址不是内部的MAC，则在数据库中找到对应的MAC地址
            //if (ycdMac.ToUpper().StartsWith(SharedData.YCD_MAC_EPON_START) == false && ycdMac.ToUpper().StartsWith(SharedData.YCD_MAC_GPON_START) == false)
            //{
            //    PRODUCT proW = new PRODUCT();
            //    //查询MAC是否解绑，若没有解绑，YCDMAC必须与MAC一致才可以绑定
            //    proW.SetWhere();
            //    proW.MAC = mac;
            //    var selectProCount = MethodWcf.SelectProductCountClient(proW);
            //    if (selectProCount.result&&selectProCount.message!="0"&&mac!=ycdMac)
            //    {
            //        AppendRichTextBox("此外部MAC已经绑定过其他的内部MAC，此外部MAC地址可能重号");
            //        FinallyDone(mac);
            //        return;
            //    }

            //    //找到此MAC绑定的内部MAC地址
            //    //selectPro = null;//重置为空
            //    proW.Clear();
            //    proW.SetWhere();
            //    proW.MAC = ycdMac;
            //    var selectPro = MethodWcf.SelectProductClient(proW);
            //    if (selectPro.result == false)
            //    {
            //        AppendRichTextBox("此外部MAC地址未绑定内部MAC，请拿到信息写入工位重新写入");
            //        FinallyDone(mac);
            //        return;
            //    }

            //    ycdMac = selectPro.value[0].YCD_MAC;//修改YCDMAC为绑定前的MAC地址
            //}
            #endregion

            #region 新判断逻辑，使用两个product

            /*新的判断逻辑，查询ycdMac对应的pro_ycd和mac对应的pro_mac
             * 1、判断ycdMac与mac是否一致，一致的话，查询一次后可以直接写入信息->second
             * 2、判断pro_mac的站位与当前站位是否一致，不一致的话，此MAC多半重号->forth
             * 3、无pro_ycd的话，不能进行下一步->first
             * 4、只有pro_ycd的话，可以直接进行下一步，写入信息->third
             * 5、有pro_ycd和pro_mac，判断ycdMac与MAC->fifth
             * 6、两个PRODUCT中的判断逻辑
             * ①ycdMac同，MAC同；（直接写入信息）
             * ②ycdMac同，MAC不同；（不存在）
             * ③ycdMac不同，MAC同；(重号的，解绑当前的MAC，要求贴新的MAC）
             * ④ycdMac不同，MAC不同；（解绑原来的MAC，绑定新的主板）
             * */

            PRODUCT productW = new PRODUCT();
            //查ycd对应的proYcd
            productW.SetWhere();
            if (ycdMac.ToUpper().StartsWith(SharedData.YCD_MAC_EPON_START) == false && ycdMac.ToUpper().StartsWith(SharedData.YCD_MAC_GPON_START) == false)
                productW.MAC = ycdMac;
            else
                productW.YCD_MAC = ycdMac;

            var selectYcdPro = MethodWcf.SelectProductClient(productW);
            if (selectYcdPro.result == false)//ycdMAC对应的product不存在
            {
                AppendRichTextBox(string.Format("查询MAC[{0}]对应的产品信息失败，请将光猫拿到信息写入重写", ycdMac));
                FinallyDone(mac);
                return;
            }

            if (selectYcdPro.value.Count != 1)
            {
                //解绑
                for (int i = 0; i < selectYcdPro.value.Count; i++)
                {
                    var product = selectYcdPro.value[i];
                    if (_nodeId == product.NODE_ID)
                    {
                        product.Clear();
                        product.SetWhere();
                        product.YCD_MAC = product.YCD_MAC;
                        product.SetUpdate();
                        product.MAC = null;

                        MethodWcf.UpdateProductClient(product);
                    }
                }

                AppendRichTextBox(string.Format("MAC[{0}]对应的产品信息为[{1}]条，请重新扫描，并联系管理员", ycdMac, selectYcdPro.value.Count));
                FinallyDone(mac);
                return;
            }

            if (ycdMac.ToUpper() == mac.ToUpper())//内外MAC一致
            {
                ycdMac = selectYcdPro.value[0].YCD_MAC;
                goto OUT;
            }

            productW.Clear();
            productW.SetWhere();
            productW.MAC = mac;
            var selectMacPro = MethodWcf.SelectProductClient(productW);

            if (selectMacPro.result == false)//没有pro_mac
            {
                ycdMac = selectYcdPro.value[0].YCD_MAC;
                goto OUT;
            }

            //MAC地址不唯一
            if (selectMacPro.value.Count != 1)
            {
                //解绑
                for (int i = 0; i < selectMacPro.value.Count; i++)
                {
                    var product = selectMacPro.value[i];
                    if (_nodeId == product.NODE_ID)
                    {
                        product.Clear();
                        product.SetWhere();
                        product.YCD_MAC = product.YCD_MAC;
                        product.SetUpdate();
                        product.MAC = null;

                        MethodWcf.UpdateProductClient(product);
                    }
                }

                AppendRichTextBox(string.Format("MAC[{0}]对应的产品信息为[{1}]条，请重新扫描，并联系管理员", mac, selectMacPro.value.Count));
                FinallyDone(mac);
                return;
            }

            if (selectMacPro.value[0].NODE_ID != _nodeId)//站位与当前站位不一致，原因是重号
            {
                AppendRichTextBox(string.Format("请贴新码，MAC[{0}]的站位ID[{1}]与当前站位ID[{2}]不一致", mac, selectMacPro.value[0].NODE_ID, _nodeId));
                FinallyDone(mac);
                return;
            }

            //提取两者的YCDMAC与MAC
            string ycdMac1 = selectYcdPro.value[0].YCD_MAC;
            string mac1 = selectYcdPro.value[0].MAC;
            string ycdMac2 = selectMacPro.value[0].YCD_MAC;
            string mac2 = selectMacPro.value[0].MAC;

            if (ycdMac1 == ycdMac2 && mac1 == mac2)
            {
                ycdMac = ycdMac1;
            }
            else if (ycdMac1 == ycdMac2 && mac1 != mac2)//数据库会拦截下来，以防万一留下来
            {
                AppendRichTextBox(string.Format("内部MAC[{0}]地址重复，请联系管理员", ycdMac1));
                FinallyDone(mac);
                return;
            }
            else if (ycdMac1 != ycdMac2 && mac1 == mac2)//这个会在判断product数量的地方拦截下来，以防万一留下来
            {
                AppendRichTextBox(string.Format("已经有一个内部MAC为[{1}]的光猫绑定了MAC[{0}]，请贴新MAC地址", mac2, ycdMac2));

                ////解绑ycdMac1与mac的对应关系，若解绑的话，则会出现没有YCDMAC的情况！
                //productW.Clear();
                //productW.YCD_MAC = ycdMac1;
                //productW.SetUpdate();
                //productW.MAC = null;

                //MethodWcf.UpdateProductClient(productW);

                FinallyDone(mac);
                return;
            }
            else if (ycdMac1 != ycdMac2 && mac1 != mac2
                && selectMacPro.value[0].END_TIME <= (DateTime.Now.Hour >= 8 ? DateTime.Now.AddHours(-6) : DateTime.Now.AddHours(-18)))
            {
                //解绑ycdMac2与mac2之间的绑定关系，4小时内未处理的不良品将解绑MAC，用于回收的MAC地址
                productW.Clear();
                productW.SetWhere();
                productW.YCD_MAC = ycdMac2;
                productW.SetUpdate();
                productW.MAC = null;
                MethodWcf.UpdateProductClient(productW);

                ////解绑ycdmac1与mac1的关系，解绑会导致找不到MAC对应的product的情况
                //productW.Clear();
                //productW.SetWhere();
                //productW.YCD_MAC = ycdMac1;
                //productW.SetUpdate();
                //productW.MAC = null;

                //MethodWcf.UpdateProductClient(productW);

                ycdMac = ycdMac1;
            }
            else
            {
                AppendRichTextBox("请贴新MAC后，再次测试");
                FinallyDone(mac);
                return;
            }

            OUT://跳转到此处
            #endregion

            //查询YCD_DEVICE，并更新Device的LightModuleSn
            YCD_DEVICE ycdW = new YCD_DEVICE();
            ycdW.SetWhere();
            ycdW.YCD_MAC = ycdMac;

            var selectYcd = MethodWcf.SelectYcdDeviceClient(ycdW);
            if (selectYcd.result == false)
            {
                AppendRichTextBox("查询YCD_MAC失败");
                FinallyDone(mac);
                return;
            }

            //判断YCDMAC与MAC的BOSA类型是否一致
            if (selectYcd.value[0].PON_TYPE != selectDevice.value[0].PONType)
            {
                AppendRichTextBox("内部MAC与外部MAC的BOSA类型不一致");
                FinallyDone(mac);
                return;
            }


            AppendRichTextBox("判断是否可以进行信息检查的工作");

            string msg = "";

            //判断是否可以开始信息检查的工作
            bool canTest = StationTest.IfCanTest(ycdMac, ref msg, _stationIp);

            //WriteLog(msg);
            AppendRichTextBox(msg);

            if (canTest == false)
            {
                //删除相关的MAC信息
                FinallyDone(mac);
                return;
            }

            //给device赋值
            selectDevice.value[0].LightModuleSN = selectYcd.value[0].LIGHT_MODULE_SN;

            //写真实的Device信息
            var checkMsg = ModemMsgCheck(selectDevice.value[0], deviceType, ycdMac, tel);

            //System.Threading.Thread.Sleep(1000);
            AppendRichTextBox("信息检查工作完成");

            if (checkMsg)
            {
                ////写真实的MAC地址
                //bool writeMac = false;
                //writeMac = TelnetSendAndRecv(tel, string.Format("flash set ELAN_MAC_ADDR {0}", mac), "=" + mac);

                //bool updateDevice = false, updateProduct = false;
                //if (writeMac)
                //{
                //    //更新BOSA_SN
                //    deviceW.SetUpdate();
                //    deviceW.LightModuleSN = selectYcd.value[0].LIGHT_MODULE_SN;
                //    updateDevice = MethodWcf.UpdateDeviceDataClient(deviceW).result;

                //    //绑定MAC与ycdMAC
                //    PRODUCT proU = new PRODUCT();
                //    proU.SetWhere();
                //    proU.YCD_MAC = ycdMac;
                //    proU.SetUpdate();
                //    proU.MAC = mac;
                //    updateProduct = MethodWcf.UpdateProductClient(proU).result;

                //    AppendRichTextBox(string.Format("更新BOSA结果为：{0}，绑定MAC结果为：{1}", updateDevice, updateProduct));
                //}

                //ADD_8.27 WIFI温补值写入
                bool updateProduct = true, updateDevice = true, writeMac = true;

                //复位
                if (updateProduct && updateDevice && writeMac)
                {
                    AppendRichTextBox("等待恢复出厂设置完成……");

                    //ResetModem(tel, deviceType.DeviceType);
                    bool resetResult = SoftShared.ResetModem(tel, ModemType.DX_926, out msg);
                    AppendRichTextBox(msg);

                    //写LOG信息
                    bool writeLogResult = StationTest.SaveTestData(ycdMac, resetResult, _log, ref msg, _stationIp);
                    AppendRichTextBox(string.Format("写LOG信息结果为：{0}，返回信息为：{1}", writeLogResult, msg));

                    System.Threading.Thread.Sleep(7000);
                    FinallyDone(mac, resetResult && writeLogResult);

                    tel.Send("exit");
                    tel.Close();
                    return;//正常返回
                }
            }

            //写LOG信息
            var writeRet = StationTest.SaveTestData(ycdMac, false, _log, ref msg, _stationIp);
            AppendRichTextBox(string.Format("写LOG信息结果为：{0}，返回信息为：{1}", writeRet, msg));

            //关闭socket
            tel.Send("exit");
            tel.Close();

            FinallyDone(mac);
        }
        /// <summary>
        /// 检查WIFI参数
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        //private bool CheckWifiMsg(YcdTelnetSecond tel)
        //{
        //    //return true;

        //    //WIFI信息检查
        //    //查询YCD_MAC对应的校准信息
        //    //           TEST_TOP testW = new TEST_TOP();
        //    //           testW.SetWhere(string.Format(@"PROCESS_ID = (
        //    //	SELECT
        //    //		TOP 1 ID
        //    //	FROM
        //    //		TRCTL.dbo.PROCESS
        //    //	WHERE
        //    //		MAC IN('{0}','{1}')
        //    //	AND NODE_ID = 20064
        //    //	AND TEST_RESULT = 'Y'
        //    //	ORDER BY
        //    //		ID DESC
        //    //)", ycdMac,mac));

        //    //           var selectTest = MethodWcf.SelectTestTopClient(testW);

        //    //           if (selectTest.result == false)
        //    //           {
        //    //               AppendRichTextBox("查询WIFI校准LOG失败");
        //    //               return false;
        //    //           }

        //    //           //从日志中截取数据
        //    //           string wifiMsg = selectTest.value[0].CONTEXT;
        //    //           int start = wifiMsg.IndexOf("READ_PA_BEGIN");
        //    //           int end = wifiMsg.IndexOf("READ_PA_END");

        //    //           if(start==-1 || end == -1)
        //    //           {
        //    //               AppendRichTextBox("此产品没有WIFI校准值日志");
        //    //               return true;
        //    //           }

        //    //           wifiMsg = wifiMsg.Substring(start, end - start + 1);

        //    //执行命令获取数据
        //    string msg;
        //    //string key;
        //    if (tel.SendAndRecv("flash get HW_WLAN0_11N_XCAP", "HW_WLAN0_11N_XCAP=", out msg))
        //    {
        //        AppendRichTextBox(msg);
        //        if (msg.Contains("HW_WLAN0_11N_XCAP=00")) return false;
        //    }
        //    else return false;

        //    if (tel.SendAndRecv("flash get HW_WLAN0_TX_POWER_CCK_A", "HW_WLAN0_TX_POWER_CCK_A=", out msg))
        //    {
        //        AppendRichTextBox(msg);
        //        if (msg.Contains("=0000000000000000000000000000")) return false;
        //        //key = "HW_WLAN0_TX_POWER_CCK_A" + msg.Substring(msg.IndexOf("="));
        //        //if (wifiMsg.Contains(key) == false) return false;
        //    }
        //    else return false;

        //    if (tel.SendAndRecv("flash get HW_WLAN0_TX_POWER_HT40_1S_A", "HW_WLAN0_TX_POWER_HT40_1S_A=", out msg))
        //    {
        //        AppendRichTextBox(msg);
        //        //key = "HW_WLAN0_TX_POWER_HT40_1S_A" + msg.Substring(msg.IndexOf("="));
        //        //if (wifiMsg.Contains(key) == false) return false;
        //        if (msg.Contains("=0000000000000000000000000000")) return false;
        //    }
        //    else return false;

        //    if (tel.SendAndRecv("flash get HW_WLAN0_TX_POWER_CCK_B", "HW_WLAN0_TX_POWER_CCK_B=", out msg))
        //    {
        //        AppendRichTextBox(msg);
        //        //key = "HW_WLAN0_TX_POWER_CCK_B" + msg.Substring(msg.IndexOf("="));
        //        //if (wifiMsg.Contains(key) == false) return false;
        //        if (msg.Contains("=0000000000000000000000000000")) return false;
        //    }
        //    else return false;

        //    if (tel.SendAndRecv("flash get HW_WLAN0_TX_POWER_HT40_1S_B", "HW_WLAN0_TX_POWER_HT40_1S_B=", out msg))
        //    {
        //        AppendRichTextBox(msg);
        //        //key = "HW_WLAN0_TX_POWER_HT40_1S_B" + msg.Substring(msg.IndexOf("="));
        //        //if (wifiMsg.Contains(key) == false) return false;
        //        if (msg.Contains("=0000000000000000000000000000")) return false;
        //    }
        //    else return false;

        //    if (tel.SendAndRecv("flash get HW_WLAN0_TX_POWER_DIFF_OFDM", "HW_WLAN0_TX_POWER_DIFF_OFDM=", out msg))
        //    {
        //        AppendRichTextBox(msg);
        //        //key = "HW_WLAN0_TX_POWER_DIFF_OFDM" + msg.Substring(msg.IndexOf("="));
        //        //if (wifiMsg.Contains(key) == false) return false;
        //        if (msg.Contains("=0000000000000000000000000000")) return false;
        //    }
        //    else return false;

        //    if (tel.SendAndRecv("flash get HW_WLAN0_TX_POWER_DIFF_HT20", "HW_WLAN0_TX_POWER_DIFF_HT20=", out msg))
        //    {
        //        AppendRichTextBox(msg);
        //        //key = "HW_WLAN0_TX_POWER_DIFF_HT20" + msg.Substring(msg.IndexOf("="));
        //        //if (wifiMsg.Contains(key) == false) return false;
        //        if (msg.Contains("=0000000000000000000000000000")) return false;
        //    }
        //    else return false;

        //    if (tel.SendAndRecv("cat /proc/wlan0/mib_rf", "#", out msg))
        //    {
        //        AppendRichTextBox(msg);
        //        if (msg.Replace(" ", "").Contains("ther:0")) return false;
        //    }
        //    else return false;

        //    return true;
        //}

        private bool ProductCheck(string mac)
        {
            //查找过程表，看有没有一条已经通过的数据
            PRODUCT productW = new PRODUCT();
            productW.SetWhere();

            productW.MAC = mac;
            productW.TEST_RESULT = "Y";
            productW.NODE_ID = _nodeId;
            productW.NODE_STATE = true;//表示工序完成

            var selectProduct = MethodWcf.SelectProductCountClient(productW);

            if (selectProduct.result && selectProduct.message == "1") return true;
            return false;
        }

        private bool ModemMsgCheck(Device_Data deviceData, Device_Type deviceType, string ycdMac, YcdTelnetSecond tel)
        {

            //判断是MTK还是R方案
            bool checkResult = false;

            checkResult = WriteDeviceR(deviceData, deviceType, tel);

            return checkResult;
        }

        private bool WriteDeviceR(Device_Data deviceData, Device_Type deviceType, YcdTelnetSecond tel)
        {
            //检查key copyright province信息是否是空值
            //if (string.IsNullOrEmpty(deviceData.HW_CIPHER) || string.IsNullOrEmpty(deviceData.HW_PROVINCE_NAME) || string.IsNullOrEmpty(deviceType.HWCopyright))
            //{
            //    SetResultOne("KEY COPYRIGHT PROVINCE三个数据为空", false);
            //    return false;
            //}

            //清除产测区
            //var writeResult = WriteAndReadMsg(tel, "default_hsnw", null, "callerAddr", null);
            //var writeResult = TelnetSendAndRecv(tel, "default_hsnw", "callerAddr");
            //if (writeResult == false) { SetResultOne("清除产测区失败", false); return false; }
            //else { SetResultOne("清除产测区成功", true); }

            //SetBobInfo(deviceType.XPONMode);

            //MAC烧录
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set ELAN_MAC_ADDR {0}", deviceData.MACAddr), "flash get ELAN_MAC_ADDR", "="+deviceData.MACAddr, "=" + deviceData.MACAddr);
            //var writeResult = TelnetSendAndRecv(tel, string.Format("flash set ELAN_MAC_ADDR {0}", deviceData.MACAddr), "=" + deviceData.MACAddr);
            //if (writeResult == false) { SetResultOne("写MAC地址失败", false); return false; }
            //else { SetResultOne("写MAC地址成功", true); }

            string msg;
            bool checkResult = SoftShared.CheckWifiMsg(tel, out msg);

            AppendRichTextBox(msg);

            if (checkResult == false)
            {
                SetResultOne("检查WIFI校准值失败", false);
                return false;
            }

            /*
            //设备序列号
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_SERIAL_NO {0}", deviceData.OUI2), "flash get HW_SERIAL_NO", "=" + deviceData.OUI2, "=" + deviceData.OUI2);
            var writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_SERIAL_NO {0}", deviceData.OUI2), "=" + deviceData.OUI2);
            if (writeResult == false) { SetResultOne("写设备序列号失败", false); return false; }
            else { SetResultOne("写设备序列号成功", true); }

            //设备型号
            //ADD_18.3.20，兼容新的类型
            string type = deviceData.DeviceType.Replace(" ", "");
            if (type.Contains("_"))
            {
                type = type.Substring(0, type.IndexOf("_"));
            }
            //deviceData.DeviceType = deviceData.DeviceType.Substring(0, deviceData.DeviceType.Length - deviceData.DeviceType.IndexOf("_"));

            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_PRODUCTCLASS {0}",type), "flash get HW_CWMP_PRODUCTCLASS", "=" + type, "=" + type);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_CWMP_PRODUCTCLASS {0}", type), "=" + type);
            if (writeResult == false) { SetResultOne("写设备型号失败", false); return false; }
            else { SetResultOne("写设备型号成功", true); }

            ////校验软件版本信息
            ////writeResult = WriteAndReadMsg(tel,  "cat /etc/swver", null, deviceType.SWVersion,null);
            //writeResult = TelnetSendAndRecv(tel, "cat /etc/swver", deviceType.SWVersion);
            //if (writeResult == false) { SetResultOne("检查软件版本失败", false); return false; }
            //else { SetResultOne("检查软件版本成功", true); }

            ////校验软件编译时间
            ////writeResult = WriteAndReadMsg(tel, "cat /etc/swver", null, deviceType.BuildTime, null);
            //writeResult = TelnetSendAndRecv(tel, "cat /etc/swver", deviceType.BuildTime);
            //if (writeResult == false) { SetResultOne("校验编译时间失败", false); return false; }
            //else { SetResultOne("校验编译时间成功", true); }

            //XPON型号
            string ponMode = null;
            if (deviceData.PONType == "STIA")
            {
                ponMode = "1";
                //写BOB信息
                //tel.Send("prolinecmd bobinfo UX GPON write 1 &\r\n");
            }
            else
            {
                ponMode = "2";
                //写BOB初始化信息
                //tel.Send("prolinecmd bobinfo UX EPON write 1 &\r\n");
            }

            //writeResult = WriteAndReadMsg(tel, string.Format("flash set PON_MODE {0}", ponMode), "flash get PON_MODE", "=" + ponMode, "=" + ponMode);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set PON_MODE {0}", ponMode), "=" + ponMode);
            if (writeResult == false) { SetResultOne("写PON的型号失败", false); return false; }
            else { SetResultOne("写PON的型号成功", true); }

            //硬件版本
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_HWVER {0}", deviceType.HWVersion), "flash get HW_HWVER", "=" + deviceType.HWVersion, "=" + deviceType.HWVersion);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_HWVER {0}", deviceType.HWVersion), "=" + deviceType.HWVersion);
            if (writeResult == false) { SetResultOne("写设备硬件版本失败", false); return false; }
            else { SetResultOne("写设备硬件版本成功", true); }

            //普通用户密码
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_USER_PASSWORD {0}", deviceData.WedPassword), "flash get DEFAULT_USER_PASSWORD", "=" + deviceData.WedPassword, "=" + deviceData.WedPassword);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set DEFAULT_USER_PASSWORD {0}", deviceData.WedPassword), "=" + deviceData.WedPassword);
            if (writeResult == false) { SetResultOne("写普通用户密码失败", false); return false; }
            else { SetResultOne("写普通用户密码成功", true); }

            //无线名称
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_SSID {0}", deviceData.WIFI_SSID), "flash get DEFAULT_WLAN_SSID", "=" + deviceData.WIFI_SSID, "=" + deviceData.WIFI_SSID);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set DEFAULT_WLAN_SSID {0}", deviceData.WIFI_SSID), "=" + deviceData.WIFI_SSID);
            if (writeResult == false) { SetResultOne("写WIFI名称失败", false); return false; }
            else { SetResultOne("写WIFI名称成功", true); }

            //无线密钥
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_WPAKEY {0}", deviceData.WIFI_Password), "flash get DEFAULT_WLAN_WPAKEY", "=" + deviceData.WIFI_Password, "=" + deviceData.WIFI_Password);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set DEFAULT_WLAN_WPAKEY {0}", deviceData.WIFI_Password), "=" + deviceData.WIFI_Password);
            if (writeResult == false) { SetResultOne("写WIFI密码失败", false); return false; }
            else { SetResultOne("写WIFI密码成功", true); }

            //ITV名称
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_SSID2ND {0}", deviceData.ITV_SSID), "flash get HW_SSID2ND", "=" + deviceData.ITV_SSID, "=" + deviceData.ITV_SSID);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_SSID2ND {0}", deviceData.ITV_SSID), "=" + deviceData.ITV_SSID);
            if (writeResult == false) { SetResultOne("写ITV SSID名称失败", false); return false; }
            else { SetResultOne("写ITV SSID成功", true); }

            //ITV密钥
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_WPAKEY2ND {0}", deviceData.ITV_Password), "flash get HW_WPAKEY2ND", "=" + deviceData.ITV_Password, "=" + deviceData.ITV_Password);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_WPAKEY2ND {0}", deviceData.ITV_Password), "=" + deviceData.ITV_Password);
            if (writeResult == false) { SetResultOne("写ITV 密码失败", false); return false; }
            else { SetResultOne("写ITV 密码成功", true); }

            //光模块型号
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_MODEL {0}", deviceData.LightModule), "flash get HW_LIGHT_MODEL", "=" + deviceData.LightModule, "=" + deviceData.LightModule);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_LIGHT_MODEL {0}", deviceData.ProductCode), "=" + deviceData.ProductCode);
            if (writeResult == false) { SetResultOne("写光模块型号失败", false); return false; }
            else { SetResultOne("写光模块型号成功", true); }

            //光模块序列号
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_SN {0}", deviceData.LightModuleSN), "flash get HW_LIGHT_SN", "=" + deviceData.LightModuleSN, "=" + deviceData.LightModuleSN);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_LIGHT_SN {0}", deviceData.LightModuleSN), "=" + deviceData.LightModuleSN);
            if (writeResult == false) { SetResultOne("写光模块序列号失败", false); return false; }
            else { SetResultOne("写光模块序列号成功", true); }

            //GPON_SN，只有GPON才写SN号码
            if (deviceData.PONType == "STIA")
            {
                //writeResult = WriteAndReadMsg(tel, string.Format("flash set GPON_SN {0}", deviceData.XPON_SN), "flash get GPON_SN", "=" + deviceData.XPON_SN, "=" + deviceData.XPON_SN);
                writeResult = TelnetSendAndRecv(tel, string.Format("flash set GPON_SN {0}", deviceData.XPON_SN), "=" + deviceData.XPON_SN);
                if (writeResult == false) { SetResultOne("写GPON_SN失败", false); return false; }
                else { SetResultOne("写GPON_SN成功", true); }
            }

            //厂商名称
            //string companyName = "youhua";
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_MANUFACTURER {0}", companyName), "flash get HW_CWMP_MANUFACTURER", "=" + companyName, "=" + companyName);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_CWMP_MANUFACTURER {0}", deviceType.Manufacturer), "=" + deviceType.Manufacturer);
            if (writeResult == false) { SetResultOne("写厂商名称失败", false); return false; }
            else { SetResultOne("写厂商名称成功", true); }

            //版本校验码key
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CIPHER {0}", deviceData.HW_CIPHER), "flash get HW_CIPHER", "=" + deviceData.HW_CIPHER, "=" + deviceData.HW_CIPHER);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_CIPHER {0}", deviceData.HW_CIPHER), "=" + deviceData.HW_CIPHER);
            if (writeResult == false) { SetResultOne("写版本校验码KEY失败", false); return false; }
            else { SetResultOne("写版本校验码KEY成功", true); }

            //软件版本校验码copyright
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_COPYRIGHT {0}", deviceType.HWCopyright), "flash get HW_COPYRIGHT", "=" + deviceType.HWCopyright, "=" + deviceType.HWCopyright);
            writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_COPYRIGHT {0}", deviceType.HWCopyright), "=" + deviceType.HWCopyright);
            if (writeResult == false) { SetResultOne("写软件版本校验码copyright失败", false); return false; }
            else { SetResultOne("写软件版本校验码copyright成功", true); }

            */

            //写省份信息
            //writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_PROVINCE_NAME {0}", deviceData.HW_PROVINCE_NAME), "flash get HW_PROVINCE_NAME", "=" + deviceData.HW_PROVINCE_NAME, "=" + deviceData.HW_PROVINCE_NAME);
            var writeResult = TelnetSendAndRecv(tel, string.Format("flash set HW_PROVINCE_NAME {0}", deviceData.HW_PROVINCE_NAME), "=" + deviceData.HW_PROVINCE_NAME);
            if (writeResult == false) { SetResultOne("写省份信息失败", false); return false; }
            else { SetResultOne("写省份信息成功", true); }

            //关闭常发光指令
            //writeResult = WriteAndReadMsg(tel, "flash set USER_FACTORY_BEFORE_RUN 0", null, "USER_FACTORY_BEFORE_RUN=", null);
            writeResult = TelnetSendAndRecv(tel, "flash set USER_FACTORY_BEFORE_RUN 0", "USER_FACTORY_BEFORE_RUN=");
            if (writeResult == false) { SetResultOne("关闭常发光失败", false); return false; }
            else { SetResultOne("关闭常发光成功", true); }

            writeResult = TelnetSendAndRecv(tel, "flash get USER_FACTORY_BEFORE_RUN", "USER_FACTORY_BEFORE_RUN=0");
            if (writeResult == false) { SetResultOne("检查长发光失败", false); return false; }
            else { SetResultOne("检查长发光成功", true); }

            return true;
        }

        /// <summary>
        /// 写R方案的信息
        /// </summary>
        /// <param name="deviceData"></param>
        /// <returns></returns>
        private bool CheckDeviceDataR(Device_Data deviceData, Device_Type deviceType, YcdTelnetSecond tel)
        {
            //检查key copyright province信息是否是空值
            if (string.IsNullOrEmpty(deviceData.HW_CIPHER) || string.IsNullOrEmpty(deviceData.HW_PROVINCE_NAME) || string.IsNullOrEmpty(deviceType.HWCopyright))
            {
                SetResultOne("KEY COPYRIGHT PROVINCE三个数据为空", false);
                return false;
            }

            //MAC烧录
            //var readResult = WriteAndReadMsg(tel, string.Format("flash set ELAN_MAC_ADDR {0}", deviceData.MACAddr), "flash get ELAN_MAC_ADDR", deviceData.MACAddr, deviceData.MACAddr);
            var readResult = TelnetSendAndRecv(tel, "flash get ELAN_MAC_ADDR", deviceData.MACAddr);
            if (readResult == false) { SetResultOne("检查MAC地址失败", false); return false; }
            else { SetResultOne("检查MAC地址成功", true); }

            //设备序列号
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_SERIAL_NO {0}", deviceData.OUI2), "flash get HW_SERIAL_NO", deviceData.OUI2, deviceData.OUI2);
            readResult = TelnetSendAndRecv(tel, "flash get HW_SERIAL_NO", deviceData.OUI2);
            if (readResult == false) { SetResultOne("检查设备序列号失败", false); return false; }
            else { SetResultOne("检查设备序列号成功", true); }


            //设备型号
            //ADD_18.3.20，兼容新的类型
            string type = deviceData.DeviceType.Replace(" ", "");
            if (type.Contains("_"))
            {
                type = type.Substring(0, type.IndexOf("_"));
            }

            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_PRODUCTCLASS {0}", type), "flash get HW_CWMP_PRODUCTCLASS", type, type);
            readResult = TelnetSendAndRecv(tel, "flash get HW_CWMP_PRODUCTCLASS", type);
            if (readResult == false) { SetResultOne("检查设备型号失败", false); return false; }
            else { SetResultOne("检查设备型号成功", true); }

            //校验软件版本信息
            //readResult = WriteAndReadMsg(tel, null, "cat /etc/swver", null, deviceType.SWVersion);
            readResult = TelnetSendAndRecv(tel, "cat /etc/swver", deviceType.SWVersion);
            if (readResult == false) { SetResultOne("检查软件版本失败", false); return false; }
            else { SetResultOne("检查软件版本成功", true); }

            //校验软件编译时间
            //readResult = WriteAndReadMsg(tel, null, "cat /etc/swver", null, deviceType.BuildTime);
            readResult = TelnetSendAndRecv(tel, "cat /etc/swver", deviceType.BuildTime);
            if (readResult == false) { SetResultOne("校验编译时间失败", false); return false; }
            else { SetResultOne("校验编译时间成功", true); }

            //硬件版本
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_HWVER {0}", deviceType.HWVersion), "flash get HW_HWVER", deviceType.HWVersion, deviceType.HWVersion);
            readResult = TelnetSendAndRecv(tel, "flash get HW_HWVER", deviceType.HWVersion);
            if (readResult == false) { SetResultOne("检查设备硬件版本失败", false); return false; }
            else { SetResultOne("检查设备硬件版本成功", true); }

            //普通用户密码
            //readResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_USER_PASSWORD {0}", deviceData.WedPassword), "flash get DEFAULT_USER_PASSWORD", deviceData.WedPassword, deviceData.WedPassword);
            readResult = TelnetSendAndRecv(tel, "flash get DEFAULT_USER_PASSWORD", deviceData.WedPassword);
            if (readResult == false) { SetResultOne("检查普通用户密码失败", false); return false; }
            else { SetResultOne("检查普通用户密码成功", true); }

            //无线名称
            //readResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_SSID {0}", deviceData.WIFI_SSID), "flash get DEFAULT_WLAN_SSID", deviceData.WIFI_SSID, deviceData.WIFI_SSID);
            readResult = TelnetSendAndRecv(tel, "flash get DEFAULT_WLAN_SSID", deviceData.WIFI_SSID);
            if (readResult == false) { SetResultOne("检查WIFI名称失败", false); return false; }
            else { SetResultOne("检查WIFI名称成功", true); }

            //无线密钥
            //readResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_WPAKEY {0}", deviceData.WIFI_Password), "flash get DEFAULT_WLAN_WPAKEY", deviceData.WIFI_Password, deviceData.WIFI_Password);
            readResult = TelnetSendAndRecv(tel, "flash get DEFAULT_WLAN_WPAKEY", deviceData.WIFI_Password);
            if (readResult == false) { SetResultOne("检查WIFI密码失败", false); return false; }
            else { SetResultOne("检查WIFI密码成功", true); }

            //ITV名称
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_SSID2ND {0}", deviceData.ITV_SSID), "flash get HW_SSID2ND", deviceData.ITV_SSID, deviceData.ITV_SSID);
            readResult = TelnetSendAndRecv(tel, "flash get HW_SSID2ND", deviceData.ITV_SSID);
            if (readResult == false) { SetResultOne("检查ITV SSID名称失败", false); return false; }
            else { SetResultOne("检查ITV SSID成功", true); }

            //ITV密钥
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_WPAKEY2ND {0}", deviceData.ITV_Password), "flash get HW_WPAKEY2ND", deviceData.ITV_Password, deviceData.ITV_Password);
            readResult = TelnetSendAndRecv(tel, "flash get HW_WPAKEY2ND", deviceData.ITV_Password);
            if (readResult == false) { SetResultOne("检查ITV 密码失败", false); return false; }
            else { SetResultOne("检查ITV 密码成功", true); }

            //光模块型号
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_MODEL {0}", deviceData.LightModule), "flash get HW_LIGHT_MODEL", deviceData.LightModule, deviceData.LightModule);
            readResult = TelnetSendAndRecv(tel, "flash get HW_LIGHT_MODEL", deviceData.ProductCode);
            if (readResult == false) { SetResultOne("检查光模块型号失败", false); return false; }
            else { SetResultOne("检查光模块型号成功", true); }

            //光模块序列号
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_SN {0}", deviceData.LightModuleSN), "flash get HW_LIGHT_SN", deviceData.LightModuleSN, deviceData.LightModuleSN);
            readResult = TelnetSendAndRecv(tel, "flash get HW_LIGHT_SN", deviceData.LightModuleSN);
            if (readResult == false) { SetResultOne("检查光模块序列号失败", false); return false; }
            else { SetResultOne("检查光模块序列号成功", true); }

            //GPON_SN，只有GPON才检查SN号码
            if (deviceType.XPONMode == "GPON")
            {
                //readResult = WriteAndReadMsg(
                //    tel,
                //    "flash get GPON_SN",
                //    string.Format("flash set GPON_SN {0}", deviceData.XPON_SN),
                //    "=" + deviceData.XPON_SN,
                //    "=" + deviceData.XPON_SN);//2018年3月20日修改，兼容跑流算法
                readResult = TelnetSendAndRecv(tel, string.Format("flash set GPON_SN {0}", deviceData.XPON_SN), "=" + deviceData.XPON_SN);//兼容跑流
                if (readResult == false) { SetResultOne("写GPON_SN失败", false); return false; }
                else { SetResultOne("写GPON_SN成功", true); }
            }

            //XPON型号
            string ponMode = null;
            if (deviceType.XPONMode == "GPON")
            {
                ponMode = "1";
            }
            else
            {
                ponMode = "2";
            }

            //readResult = WriteAndReadMsg(tel, string.Format("flash set PON_MODE {0}", ponMode), "flash get PON_MODE", ponMode, ponMode);
            readResult = TelnetSendAndRecv(tel, "flash get PON_MODE", ponMode);
            if (readResult == false) { SetResultOne("检查PON的型号失败", false); return false; }
            else { SetResultOne("检查PON的型号成功", true); }

            //厂商名称
            string companyName = "youhua";
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_MANUFACTURER {0}", companyName), "flash get HW_CWMP_MANUFACTURER", companyName, companyName);
            readResult = TelnetSendAndRecv(tel, "flash get HW_CWMP_MANUFACTURER", companyName);
            if (readResult == false) { SetResultOne("检查厂商名称失败", false); return false; }
            else { SetResultOne("检查厂商名称成功", true); }

            //版本校验码key
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_CIPHER {0}", deviceData.HW_CIPHER), "flash get HW_CIPHER", deviceData.HW_CIPHER, deviceData.HW_CIPHER);
            readResult = TelnetSendAndRecv(tel, "flash get HW_CIPHER", deviceData.HW_CIPHER);
            if (readResult == false) { SetResultOne("检查版本校验码KEY失败", false); return false; }
            else { SetResultOne("检查版本校验码KEY成功", true); }

            //软件版本校验码copyright
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_COPYRIGHT {0}", deviceType.HWCopyright), "flash get HW_COPYRIGHT", deviceType.HWCopyright, deviceType.HWCopyright);
            readResult = TelnetSendAndRecv(tel, "flash get HW_COPYRIGHT", deviceType.HWCopyright);
            if (readResult == false) { SetResultOne("检查软件版本校验码copyright失败", false); return false; }
            else { SetResultOne("检查软件版本校验码copyright成功", true); }

            //检查省份信息
            //readResult = WriteAndReadMsg(tel, string.Format("flash set HW_PROVINCE_NAME {0}", deviceData.HW_PROVINCE_NAME), "flash get HW_PROVINCE_NAME", deviceData.HW_PROVINCE_NAME, deviceData.HW_PROVINCE_NAME);
            readResult = TelnetSendAndRecv(tel, "flash get HW_PROVINCE_NAME", deviceData.HW_PROVINCE_NAME);
            if (readResult == false) { SetResultOne("检查省份信息失败", false); return false; }
            else { SetResultOne("检查省份信息成功", true); }

            //检查长发光是否关闭了
            //关闭常发光指令
            //readResult = WriteAndReadMsg(tel, null, "flash get USER_FACTORY_BEFORE_RUN", null, "USER_FACTORY_BEFORE_RUN=0");
            readResult = TelnetSendAndRecv(tel, "flash get USER_FACTORY_BEFORE_RUN", "USER_FACTORY_BEFORE_RUN=0");
            if (readResult == false) { SetResultOne("检查长发光，未关闭", false); return false; }
            else { SetResultOne("检查长发光，已关闭", true); }

            return true;
        }
        /// <summary>
        /// 检查MTK方案的信息
        /// </summary>
        /// <param name="deviceData"></param>
        /// <returns></returns>
        private bool CheckDeviceDataMtk(Device_Data deviceData, Device_Type deviceType, YcdTelnetSecond tel)
        {
            ////清除区域指令
            //var writeResult = WriteAndReadMsg(tel, "prolinecmd clear 1", null, "write", null);
            //if (writeResult == false) { SetResultOne("清除区域指令失败", false); return false; }
            //else { SetResultOne("清除区域指令成功", true); }


            //检查MAC
            var writeResult = WriteAndReadMsg(tel, string.Format("sys mac {0} -n", deviceData.MACAddr), null, "addr", null);
            if (writeResult == false) { SetResultOne("检查MAC地址失败", false); return false; }
            else { SetResultOne("检查MAC地址成功", true); }

            //检查productclass
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd productclass set {0}", deviceData.DeviceType.Replace(" ", ""))
                , "prolinecmd productclass display"
                , "readflash"
                , deviceData.DeviceType.Replace(" ", ""));

            if (writeResult == false) { SetResultOne("检查Productclass失败", false); return false; }
            else
            {
                SetResultOne("检查Productclass成功", true);
            }
            //检查oui1
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd manufacturerOUI set  {0}", deviceData.OUI1)
                , "prolinecmd manufacturerOUI display"
                , "readflash"
                , deviceData.OUI1);

            if (writeResult == false) { SetResultOne("检查OUI1失败", false); return false; }
            else { SetResultOne("检查OUI1成功", true); }
            //检查oui2
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd serialnum set  {0}", deviceData.OUI2)
                , "prolinecmd serialnum display"
                , "readflash"
                , deviceData.OUI2);

            if (writeResult == false) { SetResultOne("检查OUI2失败", false); return false; }
            else { SetResultOne("检查OUI2成功", true); }
            //检查硬件版本信息
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd hwver set  {0}", deviceType.HWVersion)
                , "prolinecmd hwver display"
                , "readflash"
                , deviceType.HWVersion);

            if (writeResult == false) { SetResultOne("检查硬件版本失败", false); return false; }
            else { SetResultOne("检查硬件版本成功", true); }
            //校验软件版本信息
            writeResult = WriteAndReadMsg(tel
                , null
                , "cat /etc/swver"
                , null
                , deviceType.SWVersion);

            if (writeResult == false) { SetResultOne("检查软件版本失败", false); return false; }
            else { SetResultOne("检查软件版本成功", true); }
            //校验软件编译时间
            writeResult = WriteAndReadMsg(tel
                , null
                , "cat /etc/swver"
                , null
                , deviceType.BuildTime);

            if (writeResult == false) { SetResultOne("校验编译时间失败", false); return false; }
            else { SetResultOne("校验编译时间成功", true); }
            //检查光模块SN
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd lightmodulesn set {0}", deviceData.LightModuleSN)
                , "prolinecmd lightmodulesn display"
                , "readflash"
                , deviceData.LightModuleSN);

            if (writeResult == false) { SetResultOne("检查光模块SN失败", false); return false; }
            else { SetResultOne("检查光模块SN成功", true); }
            //检查光模块型号
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd lightmodule set {0}", deviceData.ProductCode)
                , "prolinecmd lightmodule display"
                , "readflash"
                , deviceData.ProductCode);

            if (writeResult == false) { SetResultOne("检查光模块型号失败", false); return false; }
            else { SetResultOne("检查光模块型号成功", true); }
            //检查WIFI SSID
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd ssid  set {0}", deviceData.WIFI_SSID)
                , "prolinecmd ssid  display"
                , "readflash"
                , deviceData.WIFI_SSID);

            if (writeResult == false) { SetResultOne("检查wifi ssid失败", false); return false; }
            else { SetResultOne("检查WiFi ssid成功", true); }
            //检查WIFI密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd wpakey  set {0}", deviceData.WIFI_Password)
                , "prolinecmd wpakey  display"
                , "readflash"
                , deviceData.WIFI_Password);

            if (writeResult == false) { SetResultOne("检查WiFi密码失败", false); return false; }
            else { SetResultOne("检查wifi密码成功", true); }
            //检查ITVSSID
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd ssid2nd  set {0}", deviceData.ITV_SSID)
                , "prolinecmd ssid2nd   display"
                , "readflash"
                , deviceData.ITV_SSID);

            if (writeResult == false) { SetResultOne("检查ITV SSID失败", false); return false; }
            else { SetResultOne("检查ITV SSID 成功", true); }
            //检查ITV密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd wpakey2nd  set {0}", deviceData.ITV_Password)
                , "prolinecmd wpakey2nd   display"
                , "readflash"
                , deviceData.ITV_Password);

            if (writeResult == false) { SetResultOne("检查ITV 密码失败", false); return false; }
            else { SetResultOne("检查ITV密码成功", true); }
            //检查web用户名
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd webAccount  set {0}", deviceData.WedUser)
                , "prolinecmd webAccount   display"
                , "readflash"
                , deviceData.WedUser);

            if (writeResult == false) { SetResultOne("检查web用户名称失败", false); return false; }
            else { SetResultOne("检查web用户名称成功", true); }
            //检查web密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd webpwd set {0}", deviceData.WedPassword)
                , "prolinecmd webpwd  display"
                , "readflash"
                , deviceData.WedPassword);

            if (writeResult == false) { SetResultOne("检查web密码失败", false); return false; }
            else { SetResultOne("检查web密码成功", true); }
            //检查XPON modem
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd xponmode set {0}", deviceType.XPONMode)
                , "prolinecmd xponmode display"
                , "readflash"
                , deviceType.XPONMode);

            if (writeResult == false) { SetResultOne("检查XPON MODEM失败", false); return false; }
            else { SetResultOne("检查XPON MODEM成功", true); }
            //检查XPON SN
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd xponsn set {0}", deviceData.XPON_SN)
                , "prolinecmd xponsn display"
                , "readflash"
                , deviceData.XPON_SN);

            if (writeResult == false) { SetResultOne("检查XPON_SN失败", false); return false; }
            else { SetResultOne("检查XPON_SN成功", true); }

            //检查长发光
            return true;
        }

        /// <summary>
        /// TELNET命令
        /// </summary>
        /// <param name="tel"></param>
        /// <param name="cmdStr"></param>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        private bool TelnetSendAndRecv(YcdTelnetSecond tel, string cmdStr, string keyWord)
        {
            if (tel == null || tel.Connected == false || string.IsNullOrEmpty(cmdStr) || string.IsNullOrEmpty(keyWord)) return false;

            //发送telnet指令_语音测试
            //tel.Send(cmdStr);

            string msg;

            //bool ret = tel.GetReturnMsg(keyWord, out msg);

            bool ret = tel.SendAndRecv(cmdStr, keyWord, out msg);

            AppendRichTextBox(msg);

            return ret;
        }

        //检查信息和回显信息，MTK和R通用
        private bool WriteAndReadMsg(YcdTelnetSecond tel, string writeCmd, string readCmd, string keyWordWrite, string keyWordRead)
        {
            if (string.IsNullOrEmpty(writeCmd) && string.IsNullOrEmpty(readCmd)) return false;

            //修改writeCmd为空，不写信息
            writeCmd = null;

            //写信息
            if (string.IsNullOrEmpty(writeCmd) == false)
            {
                //tel.Send(writeCmd);

                string value;
                //bool hasKey = tel.GetReturnMsg(keyWordWrite.Trim(), out value);

                bool hasKey = tel.SendAndRecv(writeCmd, keyWordWrite, out value);

                //写LOG
                //WriteLog(value);
                AppendRichTextBox(value);

                if (hasKey == false) return false;
            }

            //读取信息
            if (string.IsNullOrEmpty(readCmd) == false)
            {
                //tel.Send(readCmd);

                string value;
                //bool hasKey = tel.GetReturnMsg(keyWordRead.Trim(), out value);
                bool hasKey = tel.SendAndRecv(readCmd, keyWordRead, out value);

                //写log
                //WriteLog(value);
                AppendRichTextBox(value);

                if (hasKey == false) return false;
            }

            return true;
        }

        private int _portOffset = DateTime.Now.Second;

        /// <summary>
        /// 连接并登陆光猫，返回类，若为空则链接失败
        /// </summary>
        /// <returns></returns>
        //private YcdTelnetSecond TelnetModem()
        //{
        //    //使用新的类YcdTelnetSecond
        //    if (_portOffset >= 500) _portOffset = 0;
        //    _portOffset++;

        //    YcdTelnetSecond telnet = new YcdTelnetSecond(_modemIp, _localIp, _localPort + _portOffset);
        //    if (telnet.Connect() == false)
        //    {
        //        return null;
        //    }

        //    System.Threading.Thread.Sleep(500);

        //    string value;
        //    if (telnet.GetReturnMsg("login", out value))
        //    {
        //        AppendRichTextBox("输入用户名称……");
        //        telnet.Send(_modemUser);
        //    }
        //    else
        //    {
        //        telnet.Send("exit");
        //        telnet.Close();
        //        return null;
        //    }


        //    //System.Threading.Thread.Sleep(3000);

        //    if (telnet.GetReturnMsg("Password:", out value))
        //    {
        //        AppendRichTextBox("输入用户密码中……");
        //        telnet.Send(_modemPwd);
        //    }
        //    else
        //    {
        //        telnet.Send("exit");
        //        telnet.Close();
        //        return null;
        //    }

        //    bool hasKey = telnet.GetReturnMsg("#", out value);

        //    if (hasKey == false) return null;

        //    AppendRichTextBox(value);

        //    return telnet;
        //}

        private void ResetModem(YcdTelnetSecond tel, string deviceType)
        {
            System.Threading.Thread.Sleep(1000);

            if (deviceType == "PT924 G")
            {
                //重置光猫
                //tel.Send("mtd erasesector 0 romfile");

                string msg;
                //bool hasKey = tel.GetReturnMsg("#", out msg);

                bool hasKey=tel.SendAndRecv("mtd erasesector 0 romfile", "#", out msg);
                //WriteLog(msg);

                AppendRichTextBox(msg);
                //tel.Send("mtd erasesector 0 reservearea");
                //hasKey = tel.GetReturnMsg("#", out msg);

                hasKey=tel.SendAndRecv("", "", out msg);
                AppendRichTextBox(msg);

                tel.Send("prolinecmd restore default");

                AppendRichTextBox("重置光猫开始……");
            }
            else
            {
                string msg;

                bool hasKey = tel.SendAndRecv("mp_default", "Please reboot system", out msg,10000);

                AppendRichTextBox(msg);

                tel.Send("reboot -f");

                AppendRichTextBox("reboot -f\r\n重置光猫开始……");
            }
        }

        /// <summary>
        /// 获取产品类型信息
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private Device_Type GetDeviceType(string type, string province)
        {
            var device = (from t in _listType
                          where t.DeviceType == type && t.PROVINCE == province
                          select t).FirstOrDefault();

            return device;
        }



        //定位到mac输入位置，重置信息
        private void MacFocus()
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action d = new Action(MacFocus);
                Invoke(d);
            }
            else
            {
                //清除list中的mac信息
                this.textBoxMacAddr.Clear();
            }
        }

        //设置textBox是否能够使用
        private void SetTextBoxReadOnly(bool enable)
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action<bool> d = new Action<bool>(SetTextBoxReadOnly);
                Invoke(d, enable);
            }
            else
            {
                this.textBoxMacAddr.ReadOnly = enable;
                //this.textBoxXponSn.Enabled = enable;
                //this.richTextBoxMsg.Enabled = enable;
            }
        }

        //将信息检查信息窗口
        private void AppendRichTextBox(string value)
        {
            if (this.richTextBoxMsg.InvokeRequired)
            {
                Action<string> d = new Action<string>(AppendRichTextBox);
                Invoke(d, new object[] { value });
            }
            else
            {
                if (value == null) return;
                if (this.richTextBoxMsg.TextLength >= 5000)
                    this.richTextBoxMsg.Clear();

                WriteLog(value);

                this.richTextBoxMsg.AppendText(value);
                this.richTextBoxMsg.AppendText("\n");
            }
        }

        //设置结果
        private void SetTestState(bool result, string msg = null)
        {
            if (labelTestResult.InvokeRequired)
            {
                Action<bool, string> d = new Action<bool, string>(SetTestState);
                Invoke(d, result, msg);
            }
            else
            {
                if (result && msg == null)
                {
                    this.labelTestResult.ForeColor = Color.Green;
                    this.labelTestResult.Text = "PASS";
                }
                else if (result == false && msg == null)
                {
                    this.labelTestResult.ForeColor = Color.Red;
                    this.labelTestResult.Text = "FAIL";
                }
                else if (msg != null && result == false)
                {
                    this.labelTestResult.ForeColor = Color.Black;
                    this.labelTestResult.Text = msg;
                }
                else if (msg != null && result)
                {
                    this.labelTestResult.ForeColor = Color.BlueViolet;
                    this.labelTestResult.Text = msg;
                }
            }
        }

        //给外部使用的获取焦点方法
        public void SetFocusMac()
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action d = new Action(MacFocus);
                Invoke(d);
            }
            else
            {
                this.textBoxMacAddr.Focus();
            }
        }

        private object lockLog = new object();//锁定LOG写
        /// <summary>
        /// 写log信息
        /// </summary>
        /// <param name="msg"></param>
        private void WriteLog(string msg)
        {
            lock (lockLog)
                _log = string.Format("{0}{1}\n", _log, msg);
        }

        /// <summary>
        /// 一个信息检查结束时操作
        /// </summary>
        private void FinallyDone(string macAddr, bool result = false)
        {
            PublicData.ListAddress.Remove(macAddr);
            SetTestState(result);//展示最后结果

            //添加测试数量
            //SetTestNum(++_testNum);

            SetTextBoxReadOnly(false);//设置textbox可用
            MacFocus();//清空mac/sn

            System.Threading.Thread.Sleep(40000);

            SetTestState(false, "WAIT");
        }

        private void richTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
            richTextBoxMsg.ScrollToCaret();
        }

        //写单项结果
        private void SetResultOne(string msg, bool result)
        {
            if (this.labelResultOne.InvokeRequired)
            {
                Action<string, bool> d = new Action<string, bool>(SetResultOne);
                Invoke(d, msg, result);
            }
            else
            {
                this.labelResultOne.Text = msg;
                if (result) this.labelResultOne.ForeColor = Color.Green;
                else this.labelResultOne.ForeColor = Color.Red;
            }
        }

    }
}
